package cn.qihua.dao.impl;

import java.util.List;

import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;

import cn.qihua.dao.IBaseProductDAO;
import cn.qihua.model.BaseProduct;
import cn.qihua.util.DateUtils;

/**
 * A data access object (DAO) providing persistence and search support for
 * BaseProduct entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see cn.qihua.model.BaseProduct
 * @author MyEclipse Persistence Tools
 */
@Transactional
public class BaseProductDAO extends BaseHibernateDAO implements IBaseProductDAO {
	private static final Logger log = LoggerFactory
			.getLogger(BaseProductDAO.class);
	protected void initDao() {
		// do nothing
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#save(cn.qihua.model.BaseProduct)
	 */
	@Override
	public Boolean save(BaseProduct transientInstance) {
		log.debug("saving BaseProduct instance");
		try {
			getCurrentSession().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#delete(cn.qihua.model.BaseProduct)
	 */
	@Override
	public void delete(BaseProduct persistentInstance) {
		log.debug("deleting BaseProduct instance");
		try {
			getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findById(java.lang.Integer)
	 */
	@Override
	public BaseProduct findById(java.lang.Integer id) {
		log.debug("getting BaseProduct instance with id: " + id);
		try {
			BaseProduct instance = (BaseProduct) getCurrentSession().get(
					"cn.qihua.model.BaseProduct", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.qihua.dao.impl.IBaseProductDAO#findByExample(cn.qihua.model.BaseProduct
	 * )
	 */
	@Override
	public List findByExample(BaseProduct instance) {
		log.debug("finding BaseProduct instance by example");
		try {
			List results = getCurrentSession()
					.createCriteria("cn.qihua.model.BaseProduct")
					.add(Example.create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByProperty(java.lang.String,
	 * java.lang.Object)
	 */
	@Override
	public List findByProperty(String propertyName, Object value) {
		log.debug("finding BaseProduct instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from BaseProduct as model where model."
					+ propertyName + "= ?";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByOrderId(java.lang.Object)
	 */
	@Override
	public List findByOrderId(Object orderId) {
		return findByProperty(ORDER_ID, orderId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByText(java.lang.Object)
	 */
	@Override
	public List findByText(Object text) {
		return findByProperty(TEXT, text);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findBySiteUrl(java.lang.Object)
	 */
	@Override
	public List findBySiteUrl(Object siteUrl) {
		return findByProperty(SITE_URL, siteUrl);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByIp(java.lang.Object)
	 */
	@Override
	public List findByIp(Object ip) {
		return findByProperty(IP, ip);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByType(java.lang.Object)
	 */
	@Override
	public List findByType(Object type) {
		return findByProperty(TYPE, type);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByUserId(java.lang.Object)
	 */
	@Override
	public List findByUserId(Object userId) {
		return findByProperty(USER_ID, userId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByUserName(java.lang.Object)
	 */
	@Override
	public List findByUserName(Object userName) {
		return findByProperty(USER_NAME, userName);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByProgress(java.lang.Object)
	 */
	@Override
	public List findByProgress(Object progress) {
		return findByProperty(PROGRESS, progress);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByYears(java.lang.Object)
	 */
	@Override
	public List findByYears(Object years) {
		return findByProperty(YEARS, years);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByIsDisuse(java.lang.Object)
	 */
	@Override
	public List findByIsDisuse(Object isDisuse) {
		return findByProperty(IS_DISUSE, isDisuse);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByStatus(java.lang.Object)
	 */
	@Override
	public List findByStatus(Object status) {
		return findByProperty(STATUS, status);
	}

	@Override
	public List findByStatus(Object status, int start, int limit) {
		return findByProperty(STATUS, status, start, limit);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByRemark(java.lang.Object)
	 */
	@Override
	public List findByRemark(Object remark) {
		return findByProperty(REMARK, remark);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findAll()
	 */
	@Override
	public List findAll() {
		log.debug("finding all BaseProduct instances");
		try {
			String queryString = "from BaseProduct";
			Query queryObject = getCurrentSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#merge(cn.qihua.model.BaseProduct)
	 */
	@Override
	public BaseProduct merge(BaseProduct detachedInstance) {
		log.debug("merging BaseProduct instance");
		try {
			BaseProduct result = (BaseProduct) getCurrentSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.qihua.dao.impl.IBaseProductDAO#attachDirty(cn.qihua.model.BaseProduct)
	 */
	@Override
	public void attachDirty(BaseProduct instance) {
		log.debug("attaching dirty BaseProduct instance");
		try {
			getCurrentSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.qihua.dao.impl.IBaseProductDAO#attachClean(cn.qihua.model.BaseProduct)
	 */
	@Override
	public void attachClean(BaseProduct instance) {
		log.debug("attaching clean BaseProduct instance");
		try {
			getCurrentSession().buildLockRequest(LockOptions.NONE).lock(
					instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#update(cn.qihua.model.BaseProduct)
	 */
	@Override
	public Boolean update(BaseProduct transientInstance) {
		log.debug("saving BaseProduct instance");
		try {
			getCurrentSession().update(transientInstance);
			return true;
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findAll(int, int)
	 */
	@Override
	public List findAll(int start, int limit) {
		log.debug("finding all BaseProduct instances");
		try {
			String queryString = "from BaseProduct";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setFirstResult(start);
			queryObject.setMaxResults(limit);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByNow(int, int, int)
	 */
	@Override
	public List findByNow(int after, int start, int limit) { // after
		try {
			String queryString = "from BaseProduct as model where model.lostDate <= ? AND model.isDisuse = FALSE";
			Query queryObject = getCurrentSession().createQuery(queryString);
			// System.out.println(DateUtils.formatDate(DateUtils.addDay(after)));
			queryObject.setString(0,
					DateUtils.formatDate(DateUtils.addDay(after)));
			queryObject.setFirstResult(start);
			queryObject.setMaxResults(limit);
			return queryObject.list();
		} catch (RuntimeException re) {
			// log.error("find by property name failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#findByProperty(java.lang.String,
	 * java.lang.Object, int, int)
	 */
	@Override
	public List findByProperty(String propertyName, Object value, int start,
			int limit) {
		try {
			String queryString = "from BaseProduct as model where model."
					+ propertyName + "= ? ORDER BY model.id DESC";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			queryObject.setFirstResult(start);
			queryObject.setMaxResults(limit);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#getTotalBySearch(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public Integer getTotalBySearch(String propertyName, String value) {
		try {
			String queryString = "select count(*) from BaseProduct where "
					+ propertyName + " LIKE '" + value + "%'";
			Query queryObject = getCurrentSession().createQuery(queryString);
			Number num = (Number) queryObject.list().get(0);
			return num.intValue();
		} catch (RuntimeException re) {
			log.error("find Product failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#searchByProperty(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public List searchByProperty(String propertyName, String value) {
		log.debug("search BaseProduct instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from BaseProduct as model where model."
					+ propertyName + " LIKE '" + value + "%'";
			Query queryObject = getCurrentSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#getTotal()
	 */
	@Override
	public Integer getTotal() {
		try {
			String queryString = "select count(*) from BaseProduct";
			Query queryObject = getCurrentSession().createQuery(queryString);

			Number num = (Number) queryObject.list().get(0);
			return num.intValue();
		} catch (RuntimeException re) {
			log.error("find Product failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#getTotalByWhere(java.lang.String)
	 */
	@Override
	public Integer getTotalByWhere(String where) {
		try {
			String queryString = "select count(*) from BaseProduct where "
					+ where;
			Query queryObject = getCurrentSession().createQuery(queryString);
			Number num = (Number) queryObject.list().get(0);
			return num.intValue();
		} catch (RuntimeException re) {
			log.error("find Product failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.qihua.dao.impl.IBaseProductDAO#getTotalByProperty(java.lang.String,
	 * java.lang.Object)
	 */
	@Override
	public Integer getTotalByProperty(String propertyName, Object value) {
		try {
			String queryString = "select count(*) from BaseProduct where "
					+ propertyName + "= ?";

			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);

			Number num = (Number) queryObject.list().get(0);
			return num.intValue();
		} catch (RuntimeException re) {
			log.error("find Product failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#changeStatus(int, int)
	 */
	@Override
	public boolean changeStatus(int id, Boolean value) {
		try {
			String queryString = "UPDATE BaseProduct SET status=? WHERE id=?)";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setBoolean(0, value);
			queryObject.setInteger(1, id);
			if (queryObject.executeUpdate() > 0) {
				return true;
			}
		} catch (RuntimeException re) {
			log.error("UPDATE Customer failed", re);
			throw re;
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#changePropertyById(int,
	 * java.lang.String, java.lang.Object)
	 */
	@Override
	public boolean changePropertyById(int id, String field, Object value) {
		try {
			StringBuffer sb = new StringBuffer("UPDATE BaseProduct SET ");
			sb.append(field);
			sb.append(" = ? WHERE id = ?");
			Query queryObject = getCurrentSession().createQuery(sb.toString());
			queryObject.setParameter(0, value);
			queryObject.setInteger(1, id);
			if (queryObject.executeUpdate() > 0) {
				return true;
			}
		} catch (RuntimeException re) {
			log.error("UPDATE Product failed", re);
			throw re;
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#changeProgress(int,
	 * java.lang.String)
	 */
	@Override
	public boolean changeProgress(int id, String value) {
		try {
			String queryString = "UPDATE BaseProduct SET progress=? WHERE id=?)";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setString(0, value);
			queryObject.setInteger(1, id);
			if (queryObject.executeUpdate() > 0) {
				return true;
			}
		} catch (RuntimeException re) {
			log.error("UPDATE Customer failed", re);
			throw re;
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.qihua.dao.impl.IBaseProductDAO#changeYears(int, int)
	 */
	@Override
	public boolean changeYears(int id, int value) {
		try {
			String queryString = "UPDATE BaseProduct SET years = years+? WHERE id=?)";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setInteger(0, value);
			queryObject.setInteger(1, id);
			if (queryObject.executeUpdate() > 0) {
				return true;
			}
		} catch (RuntimeException re) {
			throw re;
		}
		return false;
	}

	public static IBaseProductDAO getFromApplicationContext(
			ApplicationContext ctx) {
		return (IBaseProductDAO) ctx.getBean("BaseProductDAO");
	}

	@Override
	public List searchByProperty(String propertyName, String value, int start,
			int limit) {
		// TODO Auto-generated method stub
		return null;
	}
}